package com.kun.sync.util;

import java.sql.*;

/**
 * <b>数据连接管理</b>
 * <p>
 * 1、数据连接创建
 * </p>
 *
 * @author zjkorder (2018/1/27 13:11)
 */
public class DatabaseConnection {

	/**
	 * <b>数据连接创建</b>
	 * <p>
	 * <tt>params.length</tt>只能为2和4
	 * </p>
	 *
	 * 
	 * @param params 连接参数
	 * @return 数据库连接
	 * @throws SQLException SQLException
	 */
	public static Connection createConnection(String[] params) throws SQLException {

		Connection connection = null;
		try {
			Class.forName(params[0]);
			if (params.length == 2) {
				connection = DriverManager.getConnection(params[1]);
			} else {
				connection = DriverManager.getConnection(params[1], params[2], params[3]);
			}
			return connection;
		} catch (ClassNotFoundException e) {
			throw new SQLException(e);
		}

	}

	/**
	 * <b>关闭数据库</b>
	 *
	 * <p>
	 * 为null 不进行关闭
	 * </p>
	 * 
	 * @param connection connection
	 * @param statement statement
	 * @param resultSet resultSet
	 * @throws SQLException 关闭异常
	 */
	public static void close(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {
		if (resultSet != null)
			resultSet.close();

		if (statement != null)
			statement.close();

		if (connection != null)
			connection.close();
	}
}
